package com.gzxw.mogublog.admin.controller;

import com.alibaba.fastjson.JSON;
import com.gzxw.mogublog.admin.global.SysConf;
import com.gzxw.mogublog.admin.security.AuthenticationService;
import com.gzxw.mogublog.base.enums.EMenuType;
import com.gzxw.mogublog.commons.config.security.LoginUser;
import com.gzxw.mogublog.commons.entity.Admin;
import com.gzxw.mogublog.commons.entity.CategoryMenu;
import com.gzxw.mogublog.commons.entity.File;
import com.gzxw.mogublog.commons.entity.Role;
import com.gzxw.mogublog.commons.feign.PictureFeignClient;
import com.gzxw.mogublog.utils.R;
import com.gzxw.mogublog.utils.StringUtils;
import com.gzxw.mogublog.xo.service.AdminService;
import com.gzxw.mogublog.xo.service.CategoryMenuService;
import com.gzxw.mogublog.xo.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/auth")
public class LoginController {

    @Autowired
    private AuthenticationService authenticationService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private CategoryMenuService categoryService;

    @Autowired
    private PictureFeignClient pictureFeignClient;

    @Value("${tokenHead}")
    private String tokenHead;

    // 1.用户登录
    @PostMapping("/login")
    public R login(String username, String password, Boolean isRememberMe) {

        // 判断账号和密码
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return R.error("200", "账号或密码不能为空!");
        }

        String token = authenticationService.login(username, password, isRememberMe);

        HashMap<String, Object> result = new HashMap<>();
        result.put(SysConf.TOKEN, tokenHead + token);
        return R.success("登录成功!", result);
    }

    // 2.获取当前用户信息
    @GetMapping("/info")
    public R info() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return R.error("500", "请进行认证!");
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Map<String, Object> map = new HashMap<>();
        // 1.返回管理员
        Admin admin = loginUser.getAdmin();
        Role role = roleService.getById(admin.getRoleUid());

        String message = pictureFeignClient.getPicture(admin.getAvatar()).getMessage();
        File file = JSON.parseObject(message, File.class);
        map.put("username", admin.getUserName());

        map.put("avatar", file.getPicUrl());

        // 2.返回管理员对应的角色
        map.put("roleList", role);
        return R.success("200", map);
    }


    @GetMapping(value = "/getMenu")
    public R getMenu() {

        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Admin admin = adminService.getAdminById(loginUser.getAdmin().getUid());
        // 获取管理的角色UID
        String roleUid = admin.getRoleUid();
        // 角色对应的菜单
        Role role = roleService.getById(roleUid);
        String categoryMenuUids = role.getCategoryMenuUids();
        // 所有分类的id
        String[] categoryIds = categoryMenuUids
                .replace("[", "")
                .replace("]", "")
                .replace("\"", "")
                .split(",");

        List<CategoryMenu> categoryMenus = categoryService.getAllMenuByIds(categoryIds);
        List<CategoryMenu> buttonList = new ArrayList<>();
        Set<String> secondMenuUidList = new HashSet<>();

        categoryMenus.forEach(item -> {
            if (item.getMenuType() == EMenuType.MENU && item.getMenuLevel() == 2) {
                secondMenuUidList.add(item.getUid());
            }
            if (item.getMenuType() == EMenuType.BUTTON && StringUtils.isNotEmpty(item.getParentUid())) {
                // 找出二级菜单
                secondMenuUidList.add(item.getParentUid());
                // 找出全部按钮
                buttonList.add(item);
            }
        });

        Collection<CategoryMenu> childCategoryMenuList = new ArrayList<>();
        Collection<CategoryMenu> parentCategoryMenuList = new ArrayList<>();
        List<String> parentCategoryMenuUids = new ArrayList<>();

        if (secondMenuUidList.size() > 0) {
            childCategoryMenuList = categoryService.getAllMenuByIds(secondMenuUidList.toArray(new String[0]));
        }

        childCategoryMenuList.forEach(item -> {
            if (item.getMenuLevel() == 2) {
                if (StringUtils.isNotEmpty(item.getParentUid())) {
                    parentCategoryMenuUids.add(item.getParentUid());
                }
            }
        });

        if (parentCategoryMenuUids.size() > 0) {
            parentCategoryMenuList = categoryService.listByIds(parentCategoryMenuUids);
        }

        List<CategoryMenu> list = new ArrayList<>(parentCategoryMenuList);
        Map<String, Object> map = new HashMap<>();
        Collections.sort(list);
        map.put("parentList", list);
        map.put("sonList", childCategoryMenuList);
        map.put("buttonList", buttonList);
        return R.success("返回成功", map);
    }

}
